package com.andreani.snore_counter;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {
    /** Called when the activity is first created. */
	
	private final String CUSTOM_ACTION = "com.andreani.snore_counter.NEW_MSG";
	private final String MSG = "CUSTOM_MSG";
		
	private IMyService mBinder;
	private int snoreCount;
	private TextView mTv;
	private BroadcastReceiver mReceiver;
	private ServiceConnection mServConn;
		
	private Button startButton;
	private Button stopButton;
	private boolean isBound = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		Log.v(getClass().getName(),"OnCreate");
		
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    
	    mTv = (TextView) findViewById(R.id.SnoreCount);
	    startButton = (Button) findViewById(R.id.StartButton);
	    stopButton = (Button) findViewById(R.id.StopButton);
	    
	    startButton.setOnClickListener(startListener);
	    stopButton.setOnClickListener(stopListener);
	    stopButton.setEnabled(false);
	    	    
	    State s = (State) getLastNonConfigurationInstance();
	    if(s != null)
	    {
	    	if(s.getText() != null) mTv.setText(s.getText());
	    	startButton.setEnabled(s.getStartButtonState());
	    	stopButton.setEnabled(s.getStopButtonState());
	    }
	}
	
	@Override
	public void onStart()
	{
		Log.v(getClass().getName(),"OnStart");
		super.onStart();
		
		if(!isBound)
		{
			mServConn =  new MyConnection();
			bindService(new Intent(Main.this,SnoreCounterService.class),mServConn,0);
			isBound = true;
		}	
		
		mReceiver = new MyReceiver();
		registerReceiver(mReceiver,new IntentFilter(CUSTOM_ACTION));
	}
	
	@Override
	public void onStop()
	{
		super.onStop();
		Log.v(getClass().getName(),"OnStop");
		
		unregisterReceiver(mReceiver);
		if (mServConn != null && isBound )
		{
			unbindService(mServConn);
			isBound = false;
			Log.v(getClass().getName(),"unBound");
		}
		
	}
	
	final View.OnClickListener startListener = new View.OnClickListener(){
		
		public void onClick(View v) {
			
		Log.v(getClass().getName(),"Start Listener");
		startService(new Intent(Main.this,SnoreCounterService.class));
		mServConn =  new MyConnection();
		bindService(new Intent(Main.this,SnoreCounterService.class),mServConn,0);
		isBound = true;
		startButton.setEnabled(false);
		stopButton.setEnabled(true);
		//TODO  make the service go foreground
		
	 	}
	};
	
	final View.OnClickListener stopListener = new View.OnClickListener(){

		@Override
		public void onClick(View v) {
			Log.v(getClass().getName(),"Stop Listener");
			
			
			unbindService(mServConn);
			isBound = false;
			mServConn = null;
			mBinder = null;
			
			stopService(new Intent(Main.this,SnoreCounterService.class));
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			
			mTv.setText("Stopped listening for Snores");
			
    	}
	};
	
	final private class MyConnection implements ServiceConnection
	{			
		@Override
		public void onServiceConnected(ComponentName name,IBinder service) {
			Log.v(getClass().getName(),"onServiceConnected");
			mBinder = (IMyService) service;
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.v(getClass().getName(),"onServiceDisconnected");
			mBinder = null;
			}
	}
	private class MyReceiver extends BroadcastReceiver
	{
		public void onReceive(Context arg0, Intent arg1) {
			if(mBinder != null)
			{
				Log.v(getClass().getName(),"OnReceive");
				//mTv.setText(arg1.getStringExtra(MSG, mTv.getText()));
				//
				switch(arg1.getIntExtra(MSG, -1))
				{
				case(0):
					    Log.v(getClass().getName(),"OnReceive:Case 0");
						snoreCount = mBinder.getCount();
				        mTv.setText("Snores: " + snoreCount);
					break;
				case(1):
					Log.v(getClass().getName(),"OnReceive:Case 1");
					mTv.setText("Determining Baseline...");
				break;
				case(2):
					Log.v(getClass().getName(),"OnReceive:Case 2");
					mTv.setText("Baseline Set: " + mBinder.getBaseline() + "\n");
				break;
				case(-2):
					Log.v(getClass().getName(),"OnReceive:Case -2");
					mTv.setText("Error! Couldn't make the directory! \n");
				break;
				case(-3):
					Log.v(getClass().getName(),"OnReceive:Case -3");
					mTv.setText("Error! SDCARD NOT MOUNTED \n");
				break;
				default:
					Log.w(getClass().getName(),"WOAH I DON'T KNOW WHAT TO DO!");
				}
			
			}
		}
	}
	
	class State
	{
		private boolean startBtnState = true;
		private boolean stopBtnState = false;
		private CharSequence savedTvText = null;
		
		public void saveViewState(View v)
		{
			Log.v(getClass().getName(),"SaveView");
			if(v instanceof Button)
			{
				if(((Button) v).getText().equals("Start Recording"))
				{
					startBtnState = ((Button) v).isEnabled();
				}else{
					stopBtnState = ((Button) v).isEnabled();
				}
			}else if(v instanceof TextView)
			{
				savedTvText =((TextView) v).getText();
			}else{
				Log.w(getClass().getName(),"View Couldn't be saved");
			}
		}
		
		public CharSequence getText()
		{
			return savedTvText;
		}
		
		public boolean getStartButtonState()
		{
			return startBtnState;
		}
		
		public boolean getStopButtonState()
		{
			return stopBtnState;
		}
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		Log.v(getClass().getName(),"onRetainNonConfigurationInstance");
		State s = new State();
		s.saveViewState(mTv);
		s.saveViewState(startButton);
		s.saveViewState(stopButton);
		return s;
	}
}